package com.king.notifier;

import java.util.concurrent.ConcurrentHashMap;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AbstractBufferedNotifier implements Notifier {

    protected final ConcurrentHashMap<String, Long> serviceNotifyTimeMap = new ConcurrentHashMap<>();

    @Override
    public final void notify(String serviceIdentifier, String msg) {
        Long lastSendTime = serviceNotifyTimeMap.get(serviceIdentifier);
        long currentTimeMillis = System.currentTimeMillis();

        if (lastSendTime == null) {
            Long value = serviceNotifyTimeMap.putIfAbsent(serviceIdentifier, currentTimeMillis);
            if (value == null) {
                doNotify(msg);
            }
        } else {
            if (currentTimeMillis - lastSendTime < 1000 * 30) {
                return;
            } else {
                if (serviceNotifyTimeMap.replace(serviceIdentifier, lastSendTime, currentTimeMillis)) {
                    doNotify(msg);
                }
            }
        }
    }

    /**
     * 留给具体的实现类去重写
     * @param msg
     */
    protected void doNotify(String msg) {
    }
}
